/* ----------------------------------------------------------
 * 文件名称：FXMLDocumentController.java
 * 
 * 作者：秦建辉
 * 
 * 微信：splashcn
 * 
 * 博客：http://www.firstsolver.com/wordpress/
 * 
 * 开发环境：
 *      NetBeans 8.1
 *      JDK 8u92
 *      
 * 版本历史：
 *      V1.1    2016年07月17日
 *              因SDK改进更新代码
 *
 *      V1.0    2014年07月31日
 *              实现人脸模板导入导出
------------------------------------------------------------ */

package com.choosefine.base.attendance.server.tcp;

import Com.FirstSolver.Splash.FaceId;
import Com.FirstSolver.Splash.FaceIdAnswer;
import Com.FirstSolver.Splash.FaceId_ErrorCode;
import Com.FirstSolver.Splash.FaceId_Item;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author 秦建辉
 */
public class FXMLDocumentController implements Initializable {
    
    private final String DeviceCharset = "GBK";
    ObjectMapper mapper=new ObjectMapper();
    @FXML
    private TextField TextFieldExportDeviceIP;
    
    @FXML
    private TextField TextFieldExportDevicePort;
    
    @FXML
    private TextField textFieldExportSecretKey;
    
    @FXML
    private TextField TextFieldExportFileName;
    
    @FXML
    private TextField TextFieldImportDeviceIP;
    
    @FXML
    private TextField TextFieldImportDevicePort;
    
    @FXML
    private TextField textFieldImportSecretKey;
    
    @FXML
    private TextField TextFieldImportFileName;
    
    @FXML
    private CheckBox CheckBoxOverlap;
    org.slf4j.Logger logger = LoggerFactory.getLogger("fxmlController");
    @FXML
    private void handleButtonSave(ActionEvent event) {
        // 获取当前应用窗体
        Stage stage = (Stage)((Button)event.getSource()).getScene().getWindow(); 
        
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
        fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Dat files", "*.dat"),new ExtensionFilter("All Files", "*.*"));
        File selectedFile = fileChooser.showSaveDialog(stage);
        if (selectedFile != null) 
        {
            TextFieldExportFileName.setText(selectedFile.getPath());
        }
    }
    
    @FXML
    private void handleButtonExport(ActionEvent event) throws Exception {
        // 获取当前应用窗体
        Stage stage = (Stage)((Button)event.getSource()).getScene().getWindow(); 
                
        // 检测导出文件路径
        String SaveFileName = TextFieldExportFileName.getText();
        if(SaveFileName.length() == 0)return;        

        try(FaceId tcpClient = new FaceId(TextFieldExportDeviceIP.getText(), Integer.parseInt(TextFieldExportDevicePort.getText()))) {
            // 设置通信密码
            tcpClient.setSecretKey(textFieldExportSecretKey.getText());   // 注意：密码和设备通信密码一致
            
            // 获取员工工号集合        
            FaceIdAnswer output = new FaceIdAnswer(); 
            FaceId_ErrorCode ErrorCode = tcpClient.Execute("GetEmployeeID()", output, DeviceCharset); 
            if (ErrorCode.equals(FaceId_ErrorCode.Success)) 
            {   // 获取所有数据项 
                FaceId_Item[] ItemCollection = FaceId_Item.GetAllItems(output.answer); 
                if (ItemCollection != null) 
                {   // 成功导出的人员数
                    int SaveIdCount = 0;  
                    try(FileWriter sw = new FileWriter(SaveFileName, false)) {
                        for (FaceId_Item item : ItemCollection) 
                        { 
                            if (item.name.equals("id"))
                            {
                                ErrorCode = tcpClient.Execute(new StringBuilder().append("GetEmployee(id=\"").append(item.value).append("\")").toString(), output, DeviceCharset);
                                if (ErrorCode.equals(FaceId_ErrorCode.Success))
                                {   // 写入人脸数据
                                    sw.write(output.answer);
                                    logger.info(output.answer);
                                    sw.write("\r\n");
                                    SaveIdCount++;
                                }
                            }  
                        } 
                        Alert alert = new Alert(Alert.AlertType.INFORMATION, "成功导出人员：" + SaveIdCount + "/" + ItemCollection.length + "！", ButtonType.OK);
                        alert.setTitle("EXIMPORT");
                        alert.setHeaderText("信息");
                        alert.showAndWait();                        
                    }
                    catch(IOException e)
                    {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "创建导出文件失败！", ButtonType.OK);
                        alert.setTitle("EXIMPORT");
                        alert.setHeaderText("错误");
                        alert.showAndWait();
                    }
                } 
            }
        }
        catch (RuntimeException | IOException e)
        {
            Alert alert = new Alert(Alert.AlertType.ERROR, "连接设备失败！", ButtonType.OK);
            alert.setTitle("EXIMPORT");
            alert.setHeaderText("错误");
            alert.showAndWait();           
        }
    }
    
    @FXML
    private void handleButtonOpen(ActionEvent event) {
        // 获取当前应用窗体
        Stage stage = (Stage)((Button)event.getSource()).getScene().getWindow(); 
        
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
        fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Dat files", "*.dat"),new ExtensionFilter("All Files", "*.*"));
        File selectedFile = fileChooser.showOpenDialog(stage);
        if (selectedFile != null) 
        {
            TextFieldImportFileName.setText(selectedFile.getPath());
        }
    }
    
    @FXML
    private void handleButtonImport(ActionEvent event) throws Exception {
        // 获取当前应用窗体
        Stage stage = (Stage)((Button)event.getSource()).getScene().getWindow(); 
        
        // 检测导入文件路径
        String OpenFileName = TextFieldImportFileName.getText();
        if(OpenFileName.length() == 0)return;
        
        // 读取文件内容       
        StringBuilder sb = new StringBuilder();                   
        try
        { 
            try (BufferedReader br = new BufferedReader(new FileReader(OpenFileName))) {
                String s;
                while((s = br.readLine()) != null) sb.append(s).append("\r\n");
            }
        }
        catch(FileNotFoundException e)
        {   
            Alert alert = new Alert(Alert.AlertType.ERROR, "导入文件不存在！", ButtonType.OK);
            alert.setTitle("EXIMPORT");
            alert.setHeaderText("错误");
            alert.showAndWait();    
            return;
        }  
        
        if(sb.length() > 0)
        {
            try(FaceId tcpClient = new FaceId(TextFieldImportDeviceIP.getText(), Integer.parseInt(TextFieldImportDevicePort.getText())))
            {
                // 设置通信密码
                tcpClient.setSecretKey(textFieldImportSecretKey.getText());   // 注意：密码和设备通信密码一致
            
                List<FaceId_Item> ItemList = new LinkedList<>();    // 人脸列表
                List<String> EmployeeIdList = new LinkedList<>();   // 工号列表
                
                // 包含二个子表达式的正则表达式
                Pattern p = Pattern.compile("Return[(]result=\"success\"\\s+(id=\"([a-z|A-Z|0-9]+)\"\\s+[^)]+)[)]");
                Matcher m = p.matcher(sb.toString());
                while(m.find())
                {
                    ItemList.add(new FaceId_Item(m.group(2), m.group(1)));
                }
                
                // 获取员工工号集合             
                FaceIdAnswer output = new FaceIdAnswer(); 
                FaceId_ErrorCode ErrorCode = tcpClient.Execute("GetEmployeeID()", output, DeviceCharset); 
                if (ErrorCode.equals(FaceId_ErrorCode.Success)) 
                {   // 获取所有数据项 
                    FaceId_Item[] ItemCollection = FaceId_Item.GetAllItems(output.answer);
                    if (ItemCollection != null)
                    {
                        for (FaceId_Item item : ItemCollection) 
                        { 
                            if (item.name.equals("id")) EmployeeIdList.add(item.value); 
                        }
                    }
                }
                
                // 导入人脸数据
                int SkipCount = 0;
                int SaveCount = 0; 
                for (FaceId_Item item : ItemList) 
                {
                    if(!CheckBoxOverlap.isSelected())
                    {
                        if(EmployeeIdList.contains(item.name))
                        {
                            SkipCount++;
                            continue;
                        }
                    }
                    
                    ErrorCode = tcpClient.Execute(new StringBuilder().append("SetEmployee(").append(item.value).append(")").toString(), output, DeviceCharset); 
                    if(ErrorCode.equals(FaceId_ErrorCode.Success))
                    {
                        SaveCount++;
                    }
                }
                
                Alert alert = new Alert(Alert.AlertType.INFORMATION, "成功/跳过/总计人员=" + SaveCount + "/" + SkipCount + "/" + ItemList.size()+ "！", ButtonType.OK);
                alert.setTitle("EXIMPORT");
                alert.setHeaderText("信息");
                alert.showAndWait();
            }
            catch (RuntimeException | IOException e)
            {  
                Alert alert = new Alert(Alert.AlertType.ERROR, "连接设备失败！", ButtonType.OK);
                alert.setTitle("EXIMPORT");
                alert.setHeaderText("错误");
                alert.showAndWait();
            }
        }
    }
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
             
    }
}
